#include <iostream>
#include <string>
#include <cstring>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <pthread.h>
#include "log.hpp"

enum
{
    SOCKET_ERR,
    CONNET_ERR
};

void UsePage(char *argv[])
{
    std::cout << "\n\r" << argv[0] << " [ip]  [port] " << std::endl
              << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        UsePage(argv);
        exit(0);
    }

    int serverport = std::stoi(argv[2]);
    std::string serverip = argv[1];

    // socket创建套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        lg_(Fatal, "socket failed , errno message : %s , errno : %d ", strerror(errno), errno);
        exit(SOCKET_ERR);
    }

    // connet连接服务器
    struct sockaddr_in server;
    server.sin_port = htons(serverport);
    server.sin_family = AF_INET;
    inet_pton(AF_INET, serverip.c_str(), &(server.sin_addr));
    unsigned int len = sizeof(server);

    while (true)
    {
        sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0)
        {
            lg_(Fatal, "socket failed , errno message : %s , errno : %d ", strerror(errno), errno);
            exit(SOCKET_ERR);
        }
        int s = connect(sockfd, (sockaddr *)&server, len);
        if (s < 0)
        {
            lg_(Fatal, "connect failed , errno message : %s , errno : %d ", strerror(errno), errno);
            exit(CONNET_ERR);
        }

        // 进行通信
        std::string message;
        char outbuffer[1024];
        std::cout << "client#";
        std::getline(std::cin, message);
        write(sockfd, message.c_str(), message.size());

        int n = read(sockfd, outbuffer, sizeof(outbuffer));
        if (n > 0)
        {
            std::cout << outbuffer << std::endl;
        }
        close(sockfd);
    }

    return 0;
}
